﻿#include "http.h"
#include "http_log.h"
#include "common_log.h"
#include <httplib/httplib.h>

Http::Http(const QString& wcsUrl) :
	m_wcsUrl(wcsUrl), m_server(std::make_unique<httplib::Server>())
{
	
}
Http::~Http()
{

}

static Http* instance = nullptr;
Http* Http::GetInstance()
{
	if (instance == nullptr) {
		instance = new Http();
	}

	return instance;
}
void Http::SetWCSUrl(const QString& wcsUrl)
{
	m_wcsUrl = wcsUrl;
}
bool Http::Start(const int port, const QString& ip) 
{
	try {
		log_info("Starting HTTP server on {}:{}", ip, port);
		if (!m_server->listen(ip.toStdString(), port)) {
			log_error("Failed to start server on {}:{}", ip, port);
			return false;
		}
		return true;
	}
	catch (const std::exception& e) {
		log_error("Server start error: {}", e.what());
		return false;
	}
}

void Http::Stop()
{
	if (m_server) {
		log_info("Stopping HTTP server");
		m_server->stop();
	}
}

bool Http::RegisterInterface(const QString& path, const ServerInter& inter, const int type)
{
	std::string pattern = path.toStdString();
	auto func = [inter](const httplib::Request& req, httplib::Response& res) {
		QByteArray data = QByteArray::fromStdString(req.body);
		QByteArray ansData;
		(inter.callback)(data, ansData);
		if (inter.log) {
			wcs_info(" {}接口, 路径：{}", inter.name, req.path);
			wcs_info(" {}接口, 请求内容：\r\n{}", inter.name, data);
			wcs_info(" {}接口, 回复内容：\r\n{}", inter.name, ansData);
		}
		res.set_content(ansData.toStdString(), "application/json");
	};

	if (type == 0) {
		m_server->Post(pattern, func);
		return true;
	} else if (type == 1) {
		m_server->Get(pattern, func);
		return true;
	}

	return false;
}



bool Http::SendGet(const QString& path, QByteArray& ans)
{
	try {
		httplib::Client cli(m_wcsUrl.toStdString());
		auto res = cli.Get(path.toStdString().c_str());
		ans = QByteArray::fromStdString(res->body);

		wcs_info("发送GET请求， 地址: {}\r\n， 内容Body: {}", m_wcsUrl + path, ans);
		if (res) {
			wcs_info("请求{}回复： 状态: Status {} \r\nBody: {}", path, res->status, res->body);
		} else {
			wcs_info("请求{}回复超时", path);
		}
		return res && res->status == 200;
	}
	catch (const std::exception& e) {
		log_error("GET request error: {}", e.what());
		return false;
	}
}
bool Http::SendPost(const QString& path, QByteArray& ans, const QByteArray& body)
{
	// 添加详细日志
	wcs_info("机械手发送POST请求：地址: {} \r\n 内容： {}", m_wcsUrl + path, body);

	try {
		httplib::Client cli(m_wcsUrl.toStdString());
		cli.set_connection_timeout(5);  // 5秒连接超时
		cli.set_read_timeout(5);        // 5秒读取超时

		// 发送请求并检查结果
		auto result = cli.Post(path.toStdString().c_str(), body.toStdString(), "application/json");

		if (result) {  // 请求成功
			ans = QByteArray::fromStdString(result->body);
			wcs_info("POST请求{}成功. 状态: {} \r\n回复：{}", path, result->status, ans);

		} else {  // 请求失败
			log_error("POST请求{}失败. 错误: {}", path, (int)result.error());
			wcs_info("POST请求{}失败. 错误: {}", path, (int)result.error());
		}

		return result && result->status == 200;
	}
	catch (const std::exception& e) {
		log_error("POST请求异常: {}", e.what());
		return false;
	}
	catch (...) {
		log_error("POST请求异常");
		return false;
	}
}

